package com.credit.mola.app.utils.dialog

import android.annotation.SuppressLint
import android.content.Context
import android.text.Editable
import android.text.TextWatcher
import android.view.Gravity
import android.view.LayoutInflater
import android.view.View
import android.view.WindowManager
import android.view.inputmethod.EditorInfo
import android.widget.RelativeLayout
import androidx.core.content.ContextCompat
import androidx.recyclerview.widget.DefaultItemAnimator
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.credit.mola.lib_baseadapter.SikadwaOnItemChildClickListener
import com.credit.mola.lib_baseadapter.SikadwaRecyclerViewAdapter
import com.credit.mola.lib_baseadapter.SikadwaViewHolderHelper
import com.credit.mola.app.R
import com.credit.mola.app.app.App
import com.credit.mola.app.databinding.DialogBindCardAddBinding
import com.credit.mola.app.pro.ProDialog
import com.credit.mola.app.utils.DensityUtils
import com.credit.mola.app.utils.config.Configs
import com.credit.mola.app.utils.event.EventType
import com.credit.mola.app.utils.gilde.ImageUtil
import com.credit.mola.app.utils.helper.CustomConfigHelper
import com.credit.mola.app.utils.http.HttpHelper
import com.credit.mola.app.utils.rv.GridDecoration
import org.json.JSONObject

/**
 * Author : wwdeng
 * Date : 2023/8/1 15:44
 * <p>
 * 每天进步一点点
 * <p>
 * Desc : 绑卡dialog
 */
class BindCardAddDialog: ProDialog {
    private lateinit var binding: DialogBindCardAddBinding
    private var mCallback: IDialogCallback? = null
    //事件备注
    private var eventRemark = ""

    var itemAdapter: ItemAdapter? = null

    constructor(context: Context?) : super(context) {}
    constructor(context: Context?, callback: IDialogCallback?) : super(context) {
        mCallback = callback
    }

    constructor(context: Context?, remark: String,callback: IDialogCallback?) : super(context) {
        mCallback = callback
        eventRemark = remark
    }

    /**
     * 设置点击回调
     */
    fun setOnClick(callback: IDialogCallback){
        this.mCallback = callback
    }

    override fun initWindow() {
        val params = window?.attributes
        params?.width = App.app.getPhoneWidth()
        params?.height = WindowManager.LayoutParams.WRAP_CONTENT
        window?.attributes = params
        window?.setWindowAnimations(R.style.dialog_slide_anim) //修改动画样式
        window?.setGravity(Gravity.BOTTOM)
    }

    override fun getRootView(): View {
        binding = DialogBindCardAddBinding.inflate(LayoutInflater.from(context))
        return binding.root
    }

    override fun initView() {
        initRecyclerView()
        showTypeDefaultView()
        checkSubmitStatus()
    }

    override fun initListener() {
        setOnClickListener(R.id.btnAjouter)

        binding.editPhone.addTextChangedListener(ITextWatcher)
        binding.editPhoneComplete.addTextChangedListener(ITextWatcher)
        binding.editPhone.onFocusChangeListener = IFocusChangeListener
        binding.editPhoneComplete.onFocusChangeListener = IFocusChangeListener
        binding.editPhone.setOnEditorActionListener { v, actionId, event ->
            if (actionId == EditorInfo.IME_ACTION_DONE){
                binding.editPhone.clearFocus()
                true
            }
            false
        }
        binding.editPhoneComplete.setOnEditorActionListener { v, actionId, event ->
            if (actionId == EditorInfo.IME_ACTION_DONE){
                binding.editPhoneComplete.clearFocus()
                true
            }
            false
        }
    }

    override fun initData() {
        val bindList = arrayListOf<JSONObject>()
        val customize = CustomConfigHelper.getCmConfigData()
        if (customize != null){
            val walletChannels = customize.optJSONArray("walletChannels")
            if (walletChannels != null && walletChannels.length() > 0){
                for (i in 0..<walletChannels.length()){
                    val item = walletChannels.optJSONObject(i)
                    item.put("isSelect", false)
                    bindList.add(item)
                }
            }
        }
        itemAdapter?.data = bindList
    }

    override fun onViewClick(v: View?) {
        when(v?.id){
            R.id.ivClose -> {//关闭
                dismiss()
            }
            R.id.btnAjouter -> {//提交
                val typeObj = getSelectTypeItem() ?: return
                if (getPhoneNumber() != getPhoneNumberComplete()){
                    showTypeErrorView()
                    return
                }
                HttpHelper.addEvent(EventType.CLICK.CLICK_USER_ACCOUNT_ADD_SUBMIT,eventRemark)
                if(mCallback != null){
                    mCallback?.onSubmitParams(typeObj,getPhoneNumber())
                }
                dismiss()
            }
        }
    }

    /**
     * 初始化类型列表
     */
    @SuppressLint("NotifyDataSetChanged")
    private fun initRecyclerView() {
        val layoutManager = GridLayoutManager(context,2)
        binding.rvType.layoutManager = layoutManager
        itemAdapter = ItemAdapter(binding.rvType)
        val leftDecoration = DensityUtils.dp2px(10f)
        binding.rvType.addItemDecoration(GridDecoration(2, leftDecoration, false))
        binding.rvType.adapter = itemAdapter
        binding.rvType.itemAnimator = DefaultItemAnimator()
        itemAdapter?.setOnItemChildClickListener(SikadwaOnItemChildClickListener { _, childView, position ->
            itemAdapter?.let {
                val model = it.getItem(position)
                if (childView.id == R.id.itemLayout) {//切换item
                    for (i in 0..<it.itemCount) {
                        val item = it.getItem(i)
                        if (i == position) {
                            item.put("isSelect", true)
                        } else {
                            item.put("isSelect", false)
                        }
                    }
                    it.notifyDataSetChanged()
                    checkSubmitStatus()
                    HttpHelper.addEvent(
                        EventType.CLICK.CLICK_USER_ACCOUNT_ADD_TYPE_CHECK,
                        model.optString("desc")
                    )
                }
            }
        })
    }

    /**
     * 输入框监听
     */
    private val ITextWatcher = object: TextWatcher{
        override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {
        }
        override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
        }
        override fun afterTextChanged(s: Editable?) {
            showTypeDefaultView()
            checkSubmitStatus()
        }
    }

    /**
     * 焦点变化监听
     */
    private val IFocusChangeListener = View.OnFocusChangeListener { v, hasFocus ->
        if (!hasFocus){
            if (v.id == R.id.editPhone){
                val mobile = binding.editPhone.text.toString().trim()
                if (mobile.isNotEmpty()){
                    HttpHelper.addEvent(EventType.FORM.FORM_USER_ACCOUNT_ADD_MOBILE,mobile)
                }
            } else {
                val mobile = binding.editPhoneComplete.text.toString().trim()
                if (mobile.isNotEmpty()){
                    HttpHelper.addEvent(EventType.FORM.FORM_USER_ACCOUNT_ADD_MOBILE,mobile)
                }
            }
        }
    }

    /**
     * 设置默认样式
     */
    private fun showTypeDefaultView(){
        binding.editPhone.setBackgroundResource(R.drawable.circle_fill_fff6f6f6)
        binding.editPhone.setTextColor(ContextCompat.getColor(context,R.color.FF8F97A9))
        binding.editPhoneComplete.setBackgroundResource(R.drawable.circle_fill_fff6f6f6)
        binding.editPhoneComplete.setTextColor(ContextCompat.getColor(context,R.color.FF8F97A9))
        binding.errorTipsLayout.visibility = View.GONE
    }

    /**
     * 设置号码错误提示
     */
    fun showTypeErrorView(){
        binding.editPhone.setBackgroundResource(R.drawable.bindcard_number_wrong_bg)
        binding.editPhone.setTextColor(ContextCompat.getColor(context,R.color.FFF55555))
        binding.editPhoneComplete.setBackgroundResource(R.drawable.bindcard_number_wrong_bg)
        binding.editPhoneComplete.setTextColor(ContextCompat.getColor(context,R.color.FFF55555))
        binding.errorTipsLayout.visibility = View.VISIBLE
    }

    /**
     * 切换Ajouter按钮是否可点击
     */
    fun checkSubmitStatus(){
        if (getSelectTypeItem() != null && getPhoneNumber().isNotEmpty() && getPhoneNumberComplete().isNotEmpty() && (getPhoneNumber() == getPhoneNumberComplete())){
            binding.btnAjouter.isEnabled = true
            binding.btnAjouter.alpha = 1f
        } else {
            binding.btnAjouter.isEnabled = false
            binding.btnAjouter.alpha = 0.4f
        }
    }

    /**
     * 获取选择的账户类型
     */
    private fun getSelectTypeItem(): JSONObject?{
        var obj: JSONObject? = null
        itemAdapter?.let {
            for (item in it.data) {
                if (item.optBoolean("isSelect", false)){
                    obj = item
                    break
                }
            }
        }
        return obj
    }

    /**
     * 获取输入的手机号码
     */
    private fun getPhoneNumber(): String{
        return binding.editPhone.text.toString()
    }

    /**
     * 获取确认手机号码
     */
    private fun getPhoneNumberComplete(): String{
        return binding.editPhoneComplete.text.toString()
    }

    class ItemAdapter(recyclerView: RecyclerView?) : SikadwaRecyclerViewAdapter<JSONObject>(recyclerView, R.layout.item_bind_card_type) {
        override fun setItemChildListener(helper: SikadwaViewHolderHelper, viewType: Int) {
            helper.setItemChildClickListener(R.id.itemLayout) //点击Item
        }
        override fun fillData(helper: SikadwaViewHolderHelper, position: Int, model: JSONObject) {
            val isSelect = model.optBoolean("isSelect", false)
            val itemLayout = helper.getView<RelativeLayout>(R.id.itemLayout)
            val imgSelect = helper.getImageView(R.id.imgSelect)
            val imgLogo = helper.getImageView(R.id.imgLogo)
            val textTitle = helper.getTextView(R.id.textTitle)
            textTitle.text = model.optString("desc")
            ImageUtil.instance?.loadImageUrl(mContext,imgLogo,model.optString("logo"),R.mipmap.img_holder)

            if (isSelect) {
                itemLayout.setBackgroundResource(R.drawable.bindcard_type_select)
                imgSelect.visibility = View.VISIBLE
                textTitle.setTextColor(ContextCompat.getColor(mContext,R.color.FF4C8FFB))
            } else {
                itemLayout.setBackgroundResource(R.drawable.bindcard_type_normal)
                imgSelect.visibility = View.GONE
                textTitle.setTextColor(ContextCompat.getColor(mContext,R.color.FF8CA8C1))
            }
        }
    }

    interface IDialogCallback {
        //按钮点击
        fun onClick(view: View?)
        //确认
        fun onSubmitParams(typeObj: JSONObject,phoneNumber: String)
    }

    override fun onStart() {
        super.onStart()
        HttpHelper.addEvent(EventType.DIALOG.DIALOG_USER_ACCOUNT_ADD_SHOW,eventRemark)
    }

    override fun dismiss() {
        super.dismiss()
        HttpHelper.addEvent(EventType.DIALOG.DIALOG_USER_ACCOUNT_ADD_DISMISS,eventRemark)
    }
}